package com.antsoft.database.mybatis;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * Created by Jason on 2017/3/6.
 */
@Aspect
@Component
public class ReadOnlyConnectionInterceptor implements Ordered {

    public static final Logger logger = LoggerFactory.getLogger(ReadOnlyConnectionInterceptor.class);
    
    @Around("@annotation(readOnlyConnection)")
    public Object proceed(ProceedingJoinPoint pjp,ReadOnlyConnection readOnlyConnection) throws Throwable {
        try {
            logger.info("set database connection to read only");
            DbContextHolder.setDbType(DbType.SLAVE);
            logger.info("程序执行开始！");
            Object result = pjp.proceed();
            logger.info("程序执行结束！");
            DbContextHolder.clearDbType();
            return result;
        }finally {
            DbContextHolder.clearDbType();
            logger.info("restore database connection");
        }
    }


    private int order;

    @Value("20")
    public void setOrder(int order) {
        this.order = order;
    }

    @Override
    public int getOrder() {
       return order;
    }

    @Pointcut(value="execution(public * *(..))")
    public void anyPublicMethod() { }
}
